//消息对象数组
var msgObjArr = new Array();

var websocket = null;

//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
    websocket = new WebSocket("ws://localhost:8080/CampusDating/websocket/"+user.id);
} else {
    console.error("不支持WebSocket");
}

//连接发生错误的回调方法
websocket.onerror = function (e) {
    console.error("WebSocket连接发生错误");
};

//连接成功建立的回调方法
websocket.onopen = function () {
    //获取所有在线用户
    // $.ajax({
    //     type: 'post',
    //     url: ctx + "/websocket/getOnlineList",
    //     data: {userId:user.id},
    //     success: function (data) {
    //         console.log(data);
    //         if (data!=null) {
    //             //列表
    //             for (var i = 0; i < data.length; i++) {
    //                 var userId = data[i].targetUser.id;
    //                 var username = data[i].targetUser.username;
    //                 var profilePhoto = data[i].targetUser.profilePhoto;
    //                 $("#friendList").append("<li><a href='#'><p hidden>"+userId+"</p><img src="+profilePhoto+" alt='user-img' class='img-circle'/><span>"+username+"</span><small class='text-success'>online</small><div id=\"hz-badge-" + userId + "\" class='hz-badge'>0</div></a></li>");
    //             }
    //
    //             //在线人数
    //             //$("#onlineCount").text(data.length);
    //         }
    //     },
    //     error: function (xhr, status, error) {
    //         console.log("ajax错误！");
    //     }
    // });

    //获取最近联系好友以及聊天记录
    console.log("连接成功");
    // $.ajax({
    //     type: 'post',
    //     url: ctx+"/userFriend/getRecentlyFriend",
    //     data: {id:user.id},
	// 	async: false,
    //     success: function (data) {
    //         console.log(data);
    //         msgObjArr = data;
    //     }
    // })
};

//接收到消息的回调方法
websocket.onmessage = function (event) {
    var messageJson = eval("(" + event.data + ")");
    console.log(messageJson);
    //普通消息(私聊)
    if (messageJson.type == "1") {
		var chatHistory = messageJson.chatHistory;
		// 找到当前聊天对象下标，并追加聊天记录
		for(var i=0;i<msgObjArr.length;i++){
			if(msgObjArr[i].targetUser.id==messageJson.sourceUserId){
				msgObjArr[i].chatHistoryList.push(chatHistory);
				break;
			}
		}
		// 获取当前子页面title
		var childTitle=$("#frameContent").contents().attr("title");
		//判断是否在聊天界面
		if(childTitle!="消息"){
			$.bootstrapGrowl("收到一条新消息,请查看");
			$.ajax({
                type: "post",
                url: ctx+"/user/getById",
                data: {id:messageJson.sourceUserId},
                success: function (data) {
                    var str = "<div style='margin-bottom: 10px;'><div class='media-img'><img src='"+data.profilePhoto+
                        "' alt=''></div><div class='info'><span class='title'>"+data.nickname+"</span><span class='sub-title'>"+
                        "<p>"+data.id+"</p>";
                    if(chatHistory.message.length>10){
                        str += chatHistory.message.substr(0,8)+"...</span></div></div>";
                    }else{
                        str += chatHistory.message+"</span></div></div>";
                    }
                    $("#showMessage").append(str);
                }
            });

		}else{
			//追加聊天信息
			$("#frameContent")[0].contentWindow.receiveMessage(messageJson);
		}
    }

    if(messageJson.type === "3"){
        $.bootstrapGrowl("收到一条新通知,请查看");
        var notice = messageJson.notice;
        var str = "<div class='media-img'><div class='icon-avatar bg-primary'>"+notice.sourceUser.username+"</div></div>"+
            "<div class='info'><span class='title'>"+notice.message+"</span><span class='sub-title'>"+notice.sendTime+"</span></div>";
        $("#showNotice").append(str);

        var count = $("#noticeCount").html();
        $("#noticeCount").html(parseInt(count)+1);
    }

    //普通消息(群聊)
    if (messageJson.type == "2"){
        //来源用户
        var srcUser = messageJson.srcUser;
        //目标用户
        var tarUser = messageJson.tarUser;
        //消息
        var message = messageJson.message;

        //最加聊天数据
        setMessageInnerHTML(username,tarUser.username, message);
    }

    //对方不在线
    if (messageJson.type == "0"){
        //消息
        var message = messageJson.message;

        $("#hz-message-body").append(
            "<div class=\"hz-message-list\" style='text-align: center;'>" +
            "<div class=\"hz-message-list-text\">" +
            "<span>" + message + "</span>" +
            "</div>" +
            "</div>");
    }

    //在线人数
    if (messageJson.type == "onlineCount") {
        //取出username
        //var onlineCount = messageJson.onlineCount;
        var profilePhoto = messageJson.profilePhoto;
        var username = messageJson.username;
        //var oldOnlineCount = $("#onlineCount").text();

        $("#friendList").append("<li><a href='#'><p hidden>"+messageJson.userId+"</p><img src='"+profilePhoto+"' alt='user-img' class='img-circle'/><span>"+username+"</span><small class='text-success'>online</small><div id=\"hz-badge-" + messageJson.userId + "\" class='hz-badge'>0</div></a></li>");
        //新旧在线人数对比
        // if (oldOnlineCount < onlineCount) {
        //     if($("#" + userName + "-status").length > 0){
        //         $("#" + userName + "-status").text("[在线]");
        //     }else{
        //         $("#hz-group-body").append("<div class=\"hz-group-list\"><span class='hz-group-list-username'>" + userName + "</span><span id=\"" + userName + "-status\">[在线]</span><div id=\"hz-badge-" + userName + "\" class='hz-badge'>0</div></div>");
        //     }
        // } else {
        //     //有人下线
        //     $("#" + userName + "-status").text("[离线]");
        // }
        // $("#onlineCount").text(onlineCount);
    }

}

//获取当前时间
function NowTime() {
    var time = new Date();
    var year = time.getFullYear();//获取年
    var month = time.getMonth() + 1;//或者月
    var day = time.getDate();//或者天
    var hour = time.getHours();//获取小时
    var minu = time.getMinutes();//获取分钟
    var second = time.getSeconds();//或者秒
    var data = year + "-";
    if (month < 10) {
        data += "0";
    }
    data += month + "-";
    if (day < 10) {
        data += "0"
    }
    data += day + " ";
    if (hour < 10) {
        data += "0"
    }
    data += hour + ":";
    if (minu < 10) {
        data += "0"
    }
    data += minu + ":";
    if (second < 10) {
        data += "0"
    }
    data += second;
    return data;
}

//格式化时间
function formatTime(time){
    time = time.toString();
    return time.substr(0,10)+" "+time.substr(11,8);
}